﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.IO;
using System.Diagnostics.CodeAnalysis;
using System.Web;
using System.Threading;
using System.ComponentModel.Composition;
using Microsoft.ComponentModel.Composition.Extensions.Web;

namespace Steve.UI
{
    public static class UrlGenerationExtensions
    {
        public static Uri ToUri(this Content obj)
        {
            if (obj == null) throw new ArgumentNullException("obj");

            return ToUriInternal(obj.IsSecure, obj.DefaultAuthority, obj.Url);
        }

        private static Uri ToUriInternal(bool isSecure, string authority, string url)
        {
            return new Uri((isSecure ? "https" : "http") + "://" + authority + url);
        }

        //TODO: this is kind of ugly, should probably remove it...
        public static Uri ToUri(this UrlObject obj)
        {
            return obj.ToUri(MefHttpApplication.ScopeManager);
        }

        private static Uri ToUri(this UrlObject obj, string authority)
        {
            if (obj == null) throw new ArgumentNullException("obj");
            if (string.IsNullOrWhiteSpace(authority)) throw new ArgumentNullException("authority");

            return ToUriInternal(obj.IsSecure, authority, obj.Url);
        }

        //TODO: this is kind of ugly, should probably remove it...
        public static Uri ToUri(this UrlObject obj, ScopedContainerManager container)
        {
            if (obj == null) throw new ArgumentNullException("obj");
            if (container == null) throw new ArgumentNullException("container");

            var repository = container.GetExportedValue<SiteExplorerRepository>();

            return obj.ToUri(repository);
        }

        public static Uri ToUri(this UrlObject obj, SiteExplorerRepository repository)
        {
            if (obj == null) throw new ArgumentNullException("obj");
            if (repository == null) throw new ArgumentNullException("repository");

            var site = repository.GetSite(obj.SiteName);
            return obj.ToUri(site.Authority);
        }
    }
}
